﻿using System;
using System.Collections.Generic;
using System.Linq;
using BusinessBingo.Model;
using BusinessBingo.Model.Interfaces;
using BusinessBingo.Queries;
using BusinessBingo.QueryHandlers.Base;
using BusinessBingo.QueryHandlers.Interfaces;
using BusinessBingo.QueryHandlers.Results;

namespace BusinessBingo.QueryHandlers
{
    public class CheckIfBingoSetIsFinishedQueryHandler : BaseQueryHandler, ICheckIfBingoSetIsFinishedQueryHandler
    {
        public CheckIfBingoSetIsFinishedQueryHandler(
            IValidationState validationState)
            : base(validationState)
        {
        }

        public CheckIfBingoSetIsFinishedQueryHandlerResult Execute(CheckIfBingoSetIsFinishedQuery checkIfBingoSetIsFinishedQuery)
        {
            CheckIfBingoSetIsFinishedQueryHandlerResult result = new CheckIfBingoSetIsFinishedQueryHandlerResult();

            if(checkIfBingoSetIsFinishedQuery == default(CheckIfBingoSetIsFinishedQuery))
                throw new ArgumentNullException("CheckIfBingoSetIsFinishedQuery");

            if(checkIfBingoSetIsFinishedQuery.BingoSet == default(BingoSet))
                this._validationState.AddError<CheckIfBingoSetIsFinishedQuery>(x => x.BingoSet, ErrorTypes.Empty);

            if (this._validationState.IsValid == false) return result;

            result.Succeeded = true;
            IList<WordPosition> wordPositions = checkIfBingoSetIsFinishedQuery.BingoSet.WordPositions;
            for (int i = 0; i < checkIfBingoSetIsFinishedQuery.BingoSet.Size; i++)
            {
                int position = i;
                int posXCount = wordPositions.Where(wp => wp.PositionX == position).Count();
                int posYCount = wordPositions.Where(wp => wp.PositionY == position).Count();
                
                if (posXCount != 0 && posYCount != 0)
                {
                    if (wordPositions.Where(wp => wp.PositionX == position).
                            All(wp => wp.Checked == true)
                        ||
                        wordPositions.Where(wp => wp.PositionY == position).
                            All(wp => wp.Checked == true))
                    {
                        result.IsFinished = true;
                        return result;
                    }
                }
            }

            return result;
        }
    }
}
